//
//  PersionlViewController.swift
//  TrafficViolation
//
//  Created by eaglelive on 2017/4/5.
//  Copyright © 2017年 eaglelive. All rights reserved.
//

import UIKit
import SnapKit
import SDWebImage
import SwiftyJSON
import Alamofire
class PersonalViewController: BaseController{
    let headerViewH: CGFloat = 170
    var personal:PersonalModel!//个人信息
    var tableView:UITableView!
    var headerView: PersonalHeaderView!
    var noticeImage:UIImageView!
    // 列表标题数组
    lazy var titleArray:[[String]] = {
        return [["实名认证"],
                ["常见问题","免责声明","意见反馈","通知","公司简介","联系我们","设置"],["关于"]]
    }()
    // 列表前面图标数组
    lazy var imageArray:[[String]] = {
        return [["name_auth"],
                ["comm_problem","disclaimer_mz","feed_back","message_center","complan_info","contact_us","setting_sz"],["version_test"]]
    }()
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        if reachability.isReachable{
            loadVersion()
        }
        //初始化表格
        tableView=UITableView.init(frame: CGRect(x: 0, y: 0, width: kScreenW, height: kScreenH - kTabBarH), style: .grouped)
        tableView.delegate=self;//实现代理
        tableView.dataSource=self;//实现数据源
        tableView.rowHeight = 35
        self.view.addSubview(tableView)
        headerView = PersonalHeaderView(frame: CGRect(x: 0, y: 0, width: kScreenW, height: headerViewH))
        tableView.tableHeaderView = headerView
        //准备数据
        personal = PersonalModel.loadPersonalFromDB(id: userID as! String)//查询用户信息
        if nil ==  personal {
            self.failOperNoticeFun(code: "000", message: "登录失效！")
        }else{
            headerView.icon = personal.icon
            headerView.nickName = personal.nickName
            tableView.reloadData()
        }
    }
}
extension PersonalViewController{
    //查看详情
    func btnClick(sender: UIButton){
        self.hidesBottomBarWhenPushed = true
        self.navigationController?.pushViewController(PersonalInfoController(), animated: true)
        self.hidesBottomBarWhenPushed = false
    }
    //查询版本
    func loadVersion(){
        Alamofire.request("\(projectUrl)/app/last/\(userID!)?tokenID=\(tokenID!)&tokenUserID=\(userID!)",method:.get, parameters:nil,headers:headers).responseJSON { (response) in
            let jsonString = response.result.value!
            let jsonDate = JSON(jsonString)
            if jsonDate["success"] == true && !jsonDate["rdata"].isEmpty{
                let currentVersion = jsonDate["rdata"]["version"].stringValue
                if currentVersion.compare(localVersion) == ComparisonResult.orderedDescending {
                    isUpdate = true
                    self.noticeImage.isHidden = false
                }else{
                    isUpdate = false
                    self.noticeImage.isHidden = true
                }
            }
        }
    }
}
//UITableView 代理 & 数据源
extension PersonalViewController:UITableViewDelegate, UITableViewDataSource{
    // MARK: 数据源
    func numberOfSections(in tableView: UITableView) -> Int {
        return titleArray.count
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        let subTitleArr = titleArray[section]
        return subTitleArr.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let subTextArr = titleArray[indexPath.section]
        let imgArr = imageArray[indexPath.section]
        
        let cellID = "cellId"
        var cell = tableView.dequeueReusableCell(withIdentifier: cellID)
        if cell == nil {
            cell = UITableViewCell(style: .value1, reuseIdentifier: cellID)
        }
        cell?.accessoryType = .disclosureIndicator
        cell?.textLabel?.text = subTextArr[indexPath.row]
        cell?.textLabel?.font = UIFont.systemFont(ofSize: 14)
        cell?.imageView?.image = UIImage(named: imgArr[indexPath.row])
        cell?.detailTextLabel?.font =  UIFont.systemFont(ofSize: 12)
        if(indexPath.section == 1 && indexPath.row == 5){//联系我们
            cell?.detailTextLabel?.textColor = UIColor.red
            cell?.detailTextLabel?.text = "0371-24950666"
            cell?.accessoryType = .none
        }
        if(indexPath.section == 2 && indexPath.row == 0){//关于版本
            noticeImage = UIImageView(image: UIImage(named: "round"))
            noticeImage.isHidden = true
            cell?.addSubview(noticeImage)
            noticeImage.snp.makeConstraints({ (make) in
                make.right.equalTo((cell?.snp.right)!).offset(-21)
                make.top.equalTo((cell?.snp.top)!).offset(3)
                make.width.height.equalTo(16)
            })
            cell?.detailTextLabel?.text = localVersion
        }
        return cell!
    }
    //选中cell时触发这个代理
    public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath){
        tableView.deselectRow(at: indexPath, animated: false)//点击完成，取消高亮
        if(indexPath.section == 0 || indexPath.section == 1){
            self.hidesBottomBarWhenPushed = true
            if(indexPath.section == 0 && indexPath.row == 0){//用户认证
                let vc = AuthViewController()
                vc.user_id = personal.userID
                self.navigationController?.pushViewController(vc, animated: true)
            }
            if(indexPath.section == 1 && indexPath.row == 0){//常见问题
                let vc = ShowHtmlInfo()
                vc.appTitle = "常见问题"
                vc.type = "sf004"
                self.navigationController?.pushViewController(vc, animated: true)
            }
            if(indexPath.section == 1 && indexPath.row == 1){//免责声明
                let vc = ShowHtmlInfo()
                vc.appTitle = "免责声明"
                vc.type = "sf002"
                self.navigationController?.pushViewController(vc, animated: true)
            }
            if(indexPath.section == 1 && indexPath.row == 2){//意见反馈
                self.navigationController?.pushViewController(OpinionController(), animated: true)
            }
            if(indexPath.section == 1 && indexPath.row == 3){//消息中心
                self.navigationController?.pushViewController(NotifyController(), animated: true)
            }
            if(indexPath.section == 1 && indexPath.row == 4){//公司介绍
                let vc = ShowHtmlInfo()
                vc.appTitle = "公司简介"
                vc.type = "sf003"
                self.navigationController?.pushViewController(vc, animated: true)
            }
            if(indexPath.section == 1 && indexPath.row == 5){//联系我们
                 UIApplication.shared.openURL(URL(string :"tel://0371-24950666")!)
            }
            if(indexPath.section == 1 && indexPath.row == 6){//设置
                let vc = PersonalInfoController()
                vc.personal = personal
                self.navigationController?.pushViewController(vc, animated: true)
            }
            self.hidesBottomBarWhenPushed = false
        }
        if(indexPath.section == 2 && indexPath.row == 0){//关于
            if isUpdate {
                let alertController = UIAlertController(title: "检查更新：车务通", message: "发现新版本,是否立即更新？", preferredStyle: .alert)
                let cancelAction = UIAlertAction(title: "暂不更新", style: .cancel, handler: nil)
                alertController.addAction(cancelAction)
                let okAction = UIAlertAction(title: "立即更新", style: .default, handler:{(UIAlertAction) -> Void in
                    //跳转到appstore更新
                    let urlString = "itms-apps://itunes.apple.com/cn/app/id\(appID)"//appID 为引用陈appstore上的唯一ID
                    let url = URL(string: urlString)
                    UIApplication.shared.openURL(url!)
                })
                alertController.addAction(okAction)
                self.present(alertController, animated: true, completion: nil)
            }
        }
    }
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.01
    }
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 5.0
    }
}
